/**
 * author:Administrator
 * date:2016/3/16
 * desc:TODO
 */

'use strict';

class CommonDao {
  constructor(model) {
    this.model = model;
  }

  /**
   * if obj.id => update
   * else insert
   *
   * @param obj
   */
  * store(obj) {
    if (!obj.id) {
      let instance = yield this.model.create(obj);
      instance = instance && instance.dataValues;
      obj.id = instance.id;
    } else {
      // update
      yield this.model.upsert(obj);
    }
  }

  /**
   * @param where, like { id:"1" }
   * @param updateAttr,like { attr1:"alue1"}
   */
  * update(where, updateAttr) {
    let values = updateAttr;
    let opt = {where: where};
    return yield this.model.update(values, opt);
  }

  * find(id) {
    let instance = yield this.model.findOne({where: {id: id}});
    return instance && instance.dataValues;
  }

  *findOne(where) {
    let instance = yield this.model.findOne({where: where});
    return instance && instance.dataValues;
  }

  *findMany(where) {
    let list = yield this.model.all({where: where});
    list = list.map(obj => obj.dataValues);
    return list;
  }
}

module.exports = CommonDao;